from django.db import models
from django.utils.translation import gettext_lazy as _
from apps.users.models import User


class Category(models.Model):
    """图书分类"""
    
    name = models.CharField(_('分类名称'), max_length=50)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name=_('父分类'))
    description = models.TextField(_('分类描述'), blank=True)
    image = models.ImageField(_('分类图片'), upload_to='categories/', blank=True, null=True)
    sort_order = models.IntegerField(_('排序'), default=0)
    is_active = models.BooleanField(_('是否激活'), default=True)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        db_table = 'categories'
        verbose_name = _('图书分类')
        verbose_name_plural = _('图书分类')
        ordering = ['sort_order', 'id']
    
    def __str__(self):
        return self.name
    
    @property
    def full_path(self):
        """获取完整分类路径"""
        path = []
        current = self
        while current:
            path.insert(0, current.name)
            current = current.parent
        return ' > '.join(path)


class Book(models.Model):
    """图书信息"""
    
    class BookStatus(models.TextChoices):
        DRAFT = 'draft', _('草稿')
        PUBLISHED = 'published', _('已发布')
        OUT_OF_STOCK = 'out_of_stock', _('缺货')
        DISCONTINUED = 'discontinued', _('已下架')
    
    merchant = models.ForeignKey(User, on_delete=models.CASCADE, related_name='books', verbose_name=_('商家'))
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='books', verbose_name=_('分类'))
    title = models.CharField(_('书名'), max_length=200)
    author = models.CharField(_('作者'), max_length=100)
    publisher = models.CharField(_('出版社'), max_length=100)
    isbn = models.CharField(_('ISBN'), max_length=13, unique=True)
    description = models.TextField(_('图书描述'))
    price = models.DecimalField(_('售价'), max_digits=10, decimal_places=2)
    original_price = models.DecimalField(_('原价'), max_digits=10, decimal_places=2)
    stock_quantity = models.IntegerField(_('库存数量'), default=0)
    sold_count = models.IntegerField(_('已售数量'), default=0)
    pages = models.IntegerField(_('页数'), blank=True, null=True)
    publish_date = models.DateField(_('出版日期'), blank=True, null=True)
    language = models.CharField(_('语言'), max_length=20, default='中文')
    cover_image = models.ImageField(_('封面图片'), upload_to='book_covers/', blank=True, null=True)
    status = models.CharField(_('状态'), max_length=20, choices=BookStatus.choices, default=BookStatus.DRAFT)
    weight = models.DecimalField(_('重量(kg)'), max_digits=6, decimal_places=3, blank=True, null=True)
    dimensions = models.CharField(_('尺寸(cm)'), max_length=50, blank=True)
    tags = models.CharField(_('标签'), max_length=200, blank=True, help_text=_('用逗号分隔'))
    is_featured = models.BooleanField(_('是否推荐'), default=False)
    is_new = models.BooleanField(_('是否新书'), default=False)
    discount = models.DecimalField(_('折扣'), max_digits=3, decimal_places=2, default=1.00)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        db_table = 'books'
        verbose_name = _('图书')
        verbose_name_plural = _('图书')
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title
    
    @property
    def final_price(self):
        """计算最终售价"""
        return round(self.price * self.discount, 2)
    
    @property
    def is_in_stock(self):
        """是否有库存"""
        return self.stock_quantity > 0
    
    @property
    def rating_average(self):
        """平均评分"""
        reviews = self.reviews.filter(is_approved=True)
        if reviews.exists():
            return round(reviews.aggregate(models.Avg('rating'))['rating__avg'], 1)
        return 0
    
    @property
    def review_count(self):
        """评论数量"""
        return self.reviews.filter(is_approved=True).count()


class BookImage(models.Model):
    """图书图片"""
    
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='images', verbose_name=_('图书'))
    image = models.ImageField(_('图片'), upload_to='book_images/')
    alt_text = models.CharField(_('替代文本'), max_length=100, blank=True)
    sort_order = models.IntegerField(_('排序'), default=0)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    
    class Meta:
        db_table = 'book_images'
        verbose_name = _('图书图片')
        verbose_name_plural = _('图书图片')
        ordering = ['sort_order']
    
    def __str__(self):
        return f"{self.book.title} - 图片{self.id}"


class Promotion(models.Model):
    """促销活动"""
    
    class PromotionType(models.TextChoices):
        DISCOUNT = 'discount', _('折扣')
        FIXED_AMOUNT = 'fixed_amount', _('固定金额')
        BUY_X_GET_Y = 'buy_x_get_y', _('买赠')
    
    title = models.CharField(_('活动标题'), max_length=100)
    description = models.TextField(_('活动描述'))
    promotion_type = models.CharField(_('促销类型'), max_length=20, choices=PromotionType.choices)
    discount_value = models.DecimalField(_('折扣值'), max_digits=5, decimal_places=2, blank=True, null=True)
    min_purchase_amount = models.DecimalField(_('最低购买金额'), max_digits=10, decimal_places=2, default=0)
    start_date = models.DateTimeField(_('开始时间'))
    end_date = models.DateTimeField(_('结束时间'))
    is_active = models.BooleanField(_('是否激活'), default=True)
    books = models.ManyToManyField(Book, related_name='promotions', verbose_name=_('参与图书'))
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        db_table = 'promotions'
        verbose_name = _('促销活动')
        verbose_name_plural = _('促销活动')
    
    def __str__(self):
        return self.title
